﻿@{
    ViewBag.Title = "DrapWithBorder";
    Layout = "~/Views/Shared/_Page.cshtml";
}

<style type="text/css">
    .mycontainer {
        width: 800px;
        height: 500px;
        border: solid 2px #333333;
        margin: 20px auto auto auto;
    }
    .draggable {
        width: 120px;
        height: 120px;
        margin: 10px;
        background-color: darkred;
        cursor: pointer;
    }
    .draggable.dragging {
        box-shadow: 5px 5px 5px #008000;
    }
</style>

<h2>Drap With Border</h2>

<div class="mycontainer">
    <div class="draggable"></div>
    <div class="draggable"></div>
    <div class="draggable"></div>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        $('.draggable').on("mousedown", function () {
            $(this).addClass('dragging');
        }).on("mousemove mouseout", function (event) {
            if ($(this).hasClass("dragging")) {
                //Get the parents position
                var parentPosition = $(this).parent().offset();

                //Don't allow the draggable element to go over the parent's left and right
                var left = (event.pageX - ($(this).width() / 2));
                var parentRight = parentPosition.left + $(this).parent().width();
                if (left > (parentRight - $(this).width())) {
                    left = (parentRight - $(this).width());
                } else if (left <= parentPosition.left) {
                    left = parentPosition.left;
                }

                //Don't allow the draggable element to go over the parent's top and bottom
                var top = (event.pageY - ($(this).height() / 2));
                var parentBottom = parentPosition.top + $(this).parent().height();
                if (top > (parentBottom - $(this).height())) {
                    top = (parentBottom - $(this).height());
                } else if (top <= parentPosition.top) {
                    top = parentPosition.top;
                }

                //Set new position
                $(this).css({
                    top: top + "px",
                    left: left + "px",
                    position: "absolute"
                });
            }
        }).on("mouseup", function () {
            $(this).removeClass('dragging');
        });
    });
</script>

